package com.service;

import com.VO.OnlineUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RedisService {
  @Autowired private RedisTemplate redisTemplate;

  String redisKey = "onlineUserList";

  // 加入当前在线用户

  public void addOnlineUser(OnlineUser onlineUser) {
    List<OnlineUser> list = new ArrayList<>();

    if (redisTemplate.hasKey(redisKey)) {
        Boolean flag=false;
        list = (List<OnlineUser>) redisTemplate.opsForValue().get(redisKey);

       for (OnlineUser ooo:list){
           if(ooo.getId().equals(onlineUser.getId())){
               flag=true;
               break;
           }
       }

        if(flag==false){
            list.add(onlineUser);
        }

        redisTemplate.opsForValue().set(redisKey, list);

    } else {

        list.add(onlineUser);
        redisTemplate.opsForValue().set(redisKey, list);

    }
  }

  // 获取当前在线用户
  public List<OnlineUser> findOnlineUserList() {

      List<OnlineUser> onlineUserList = new ArrayList<>();

      if (redisTemplate.hasKey(redisKey)) {
        onlineUserList = (List<OnlineUser>) redisTemplate.opsForValue().get(redisKey);
        return onlineUserList;
      } else {
        return onlineUserList;
      }

  }

  // 删除当前在线用户

  public void deleteOnlineUser(Integer id) {
    List<OnlineUser> list = new ArrayList<>();


      if (redisTemplate.hasKey(redisKey)) {

        list = (List<OnlineUser>) redisTemplate.opsForValue().get(redisKey);

        List<OnlineUser> collect =
            list.stream().filter(s -> !id.equals(s.getId())).collect(Collectors.toList());

        redisTemplate.opsForValue().set(redisKey, collect);

      } else {
        redisTemplate.opsForValue().set(redisKey, list);
      }

  }
}
